package zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class DecompressUtil {
	public static String HOTFIX_PERFIX = "hotfix-";
	public static String HOTFIX_SUFFIX = ".zip";

	/**
	 * 解压缩zip文件
	 * 
	 * @param fileAddr
	 *            zip文件地址
	 * @param desFolderAddr
	 *            目标文件夹地址
	 */
	public static void decompress(String fileAddr, String desFolderAddr) {
		int fileCount = 0;
		try {
			ZipInputStream Zin = new ZipInputStream(new FileInputStream(fileAddr));// 输入源zip路径
			BufferedInputStream Bin = new BufferedInputStream(Zin);
			String Parent = desFolderAddr; // 输出路径（文件夹目录）"
			File Fout = null;
			ZipEntry entry;
			File zipFile = new File(fileAddr);
			String zipFileName = zipFile.getName();
			String _zipFileName = zipFileName.substring(0, zipFileName.lastIndexOf("."));
			try {
				while ((entry = Zin.getNextEntry()) != null) {
					if (entry.isDirectory())
						continue;
					String entryName = entry.getName();
					if (entryName.contains("~"))
						continue;
					if (entryName.startsWith(_zipFileName)) {
						entryName = entryName.substring(_zipFileName.length());
					}
					//如果为备注文件，则文件续写
					boolean append = false;
					String readme = "readme.txt";
					String sql = "sql.txt";
					String mssql = "sql(mssql).txt";
					String mysql = "sql(mysql).txt";
					String oracle = "sql(oracle).txt";
					if(entryName.endsWith(readme)
							||entryName.endsWith(sql)
							||entryName.endsWith(mssql)
							||entryName.endsWith(mysql)
							||entryName.endsWith(oracle))
						append=true;
					//
					String override = "	覆盖";
					if(append)
						override = "	续写";
					Fout = new File(Parent, entryName);
					if (!Fout.exists()) {
						(new File(Fout.getParent())).mkdirs();
						System.out.println("		" + entryName);
					}else{
						System.out.println(override + entryName);
					}
					FileOutputStream out = new FileOutputStream(Fout,append);
					BufferedOutputStream Bout = new BufferedOutputStream(out);
					int b;
					while ((b = Bin.read()) != -1) {
						Bout.write(b);
					}
					Bout.close();
					out.close();
					fileCount++;
				}
				Bin.close();
				Zin.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println("总文件数：" + fileCount);
	}

}